package com.tanhua.api.impl.mongo;

import com.tanhua.api.mongo.QuestionBankApi;
import com.tanhua.domain.mongo.Options;
import com.tanhua.domain.mongo.Questionnaire;
import com.tanhua.domain.mongo.Subject;
import com.tanhua.domain.vo.QuestionsVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class QuestionBankApiImpl implements QuestionBankApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public List<Questionnaire> findAllQuestionnaire() {


        Query query = new Query();
        List<Questionnaire> questionnaires = mongoTemplate.find(query, Questionnaire.class);

        return questionnaires;
    }

    @Override
    public Questionnaire createQuestionnaire(QuestionsVo vo) {
        Long id = idService.getNextId("questionnaire");
        Questionnaire q = new Questionnaire();
        q.setQuestionId("A"+id);
        q.setName(vo.getTitle());
        q.setLevel(vo.getLevelStr());
        q.setStar(vo.getStarNum());
        q.setIsLock(1);
        q.setCover("https://tanhuazc.oss-cn-beijing.aliyuncs.com/images/2021/08/18/1629295496395.jpg");

        Questionnaire insert = mongoTemplate.insert(q);
        return insert;
    }

    @Override
    public Subject insertSubject(Subject subject) {
        String titleId = subject.getTitleId();
        subject.setTitleId(titleId+idService.getNextId("optionId"));
        Subject insert = mongoTemplate.insert(subject);
        return insert;
    }

    @Override
    public Options inserOptions(Options options) {
        Options insert = mongoTemplate.insert(options);
        return insert;
    }

    @Override
    public List<Subject> getQuestions(String questionId) {
        Query query = new Query(Criteria.where("questionId").is(questionId));
        List<Subject> l = mongoTemplate.find(query, Subject.class);
        return l;
    }

    @Override
    public  List<Options>  getOptions(String titleId) {
        Query query = new Query(Criteria.where("titleId").is(titleId));
        List<Options> options = mongoTemplate.find(query, Options.class);
        return options;
    }

    @Override
    public Questionnaire getQuestionnaire(String id) {

        Questionnaire questionId = mongoTemplate.findOne(new Query(Criteria.where("questionId").is(id)), Questionnaire.class);
        return questionId;
    }
}
